import { useState, useEffect } from "react";
import { useModel } from "umi";
import { Form, Input, Select, Button, message, Space, Dropdown, Row, Col, Cascader } from "antd";
import { DownOutlined } from "@ant-design/icons";
import { useReactive } from "ahooks";

import useAreaCode from "../../hooks/useAreaCode";
import useCreateStore from "../../hooks/store/useCreateStore";
import useStaff from "../../hooks/staff/useStaff";
import useCheckStoreName from "../../hooks/store/useCheckStoreName";
import useAllAffiliates from "../../hooks/affiliate/useAllAffiliates";

const AddStoreForm = ({ oiType, reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");
    const { loadAreaData, areas } = useAreaCode();

    const { loading: staffLoading, staffs } = useStaff({});
    const { loading: affiliateLoading, loadAllAffiliates, affiliates } = useAllAffiliates();

    const { checkStoreName } = useCheckStoreName();
    const { createStore, submitLoading } = useCreateStore();

    const [form] = Form.useForm();

    const [selectedOfficeLocation, setSelectedOfficeLocation] = useState([]);

    useEffect(() => {
        // form.setFieldsValue({ [["ptInfo", "oaName"]]: "sasdfadsf" });
    }, []);

    const state = useReactive({
        loading: false,
        maInfo: {},
        asInfo: {},
    });

    let onFinish = async (values) => {
        values.oiType = oiType;
        values.maInfo = state.maInfo || {};
        values.asInfo = state.asInfo || {};
        values.oiZoja = selectedOfficeLocation.map((item) => ({ id: item.id, text: item.text }));

        let affiliate = affiliates.find((item) => item.oaName === values.ptInfo?.oaName);
        values.ptInfo = affiliate ? { ...values.ptInfo, ...affiliate } : values.ptInfo;

        let res = await createStore(values);

        if (res) {
            form.resetFields();
            message.success("成功创建门店信息");
            reloadData();
            onCloseGlobalModal();
        }
    };

    const oiNameValidator = async (rule, value) => {
        if (value && validates.titleAndName(value) && value.length < 31) {
            let res = await checkStoreName({ oiName: value });
            if (res === null) return Promise.reject("检查门店名称出错");
            return res > 0 ? Promise.reject("门店名称重复！") : Promise.resolve();
        } else {
            return Promise.reject("门店名称只能输入中文、英文、数字，最多30个汉字");
        }
    };

    const onOfficeLocationChange = (value, selectedOptions) => {
        setSelectedOfficeLocation(selectedOptions);
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish} style={{ padding: 10 }}>
            {oiType === "合作门店" && (
                <Row gutter={10}>
                    <Col span={18}>
                        <Form.Item label="合作组织名称" name={["ptInfo", "oaName"]} validateTrigger="onBlur" rules={[{ required: true }]}>
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Dropdown
                            menu={{
                                items: affiliates.map((item) => ({ label: item.oaName, key: item.oaName })),
                                onClick: ({ key }) => form.setFieldsValue({ ptInfo: { oaName: key } }),
                            }}
                            trigger={["click"]}
                            disabled={!affiliates || affiliates.length === 0}
                        >
                            <Button icon={<DownOutlined />} disabled={!affiliates || affiliates.length === 0} style={{ marginTop: 30 }}>
                                选择关联组织
                            </Button>
                        </Dropdown>
                    </Col>
                </Row>
            )}

            {oiType === "合作门店" && (
                <Row gutter={10}>
                    <Col span={12}>
                        <Form.Item label="联系人" name={["ptInfo", "contactName"]} rules={[{ required: true }]}>
                            <Input placeholder="请输入" />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="联系电话" name={["ptInfo", "contactPhone"]} rules={[{ required: true }]}>
                            <Input placeholder="请输入" />
                        </Form.Item>
                    </Col>
                </Row>
            )}

            <Row gutter={10}>
                <Col span={18}>
                    <Form.Item label="门店名称" name="oiName" validateTrigger="onBlur" rules={[{ required: true, validator: oiNameValidator }]}>
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
                <Col span={6}>
                    <Form.Item label="联系电话" name="oiPhon">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={10}>
                <Col span={12}>
                    <Form.Item label="负责人(店长)" name="maInfo" rules={[{ required: true }]}>
                        <Select
                            loading={staffLoading}
                            placeholder="请选择"
                            options={staffs}
                            fieldNames={{ label: "osName", value: "osUuid" }}
                            onChange={(value, option) => (state.maInfo = { osUuid: option.osUuid, osName: option.osName })}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="管理人" name="asInfo">
                        <Select
                            loading={staffLoading}
                            placeholder="请选择"
                            options={staffs}
                            fieldNames={{ label: "osName", value: "osUuid" }}
                            onChange={(value, option) => (state.asInfo = { osUuid: option.osUuid, osName: option.osName })}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item label="所在地区" name="oiZoja" rules={[{ required: true, message: "请选择门店所在地" }]}>
                <Cascader placeholder="请选择" options={areas} loadData={loadAreaData} onChange={onOfficeLocationChange} fieldNames={{ label: "text", value: "id" }} />
            </Form.Item>

            <Row gutter={10}>
                <Col span={12}>
                    <Form.Item label="所在社区" name="oiComm">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="所在小区" name="oiEsta">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item label="详细地址" name="oiAddr">
                <Input placeholder="请输入" />
            </Form.Item>

            <Row gutter={10}>
                <Col span={12}>
                    <Form.Item label="地图经度" name="radius">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="地图纬度" name="latitude">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item label="职能说明" name="oiDesc">
                <Input.TextArea placeholder="请输入" />
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={submitLoading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={submitLoading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default AddStoreForm;
